package org.redpig.mimall.service.impl;

import org.redpig.mimall.dao.UserMapper;
import org.redpig.mimall.enums.RoleEnum;
import org.redpig.mimall.pojo.User;
import org.redpig.mimall.service.IUserService;
import org.redpig.mimall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static org.redpig.mimall.enums.ResponseEnum.*;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseVo<User> register(User user) {

//        errorSimulator();

        //username和email不能重复
        if (userMapper.countByUsername(user.getUsername()) > 0) {
            return ResponseVo.error(USERNAME_EXIST);
        }

        if (userMapper.countByEmail(user.getEmail()) > 0)
            return ResponseVo.error(EMAIL_EXIST);

        //注册用户都是普通用户
        user.setRole(RoleEnum.CUSTOMER.getCode());

        //MD5摘要算法
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //写入数据库
        if (userMapper.insertSelective(user) == 0)
            return ResponseVo.error(ERROR);
        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        //用户名或密码错误
        if (null == user) {
            //用户不存在
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        if (!user.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
            //密码错误
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }

        //避免密码返回
        user.setPassword("");
        return ResponseVo.success(user);
    }

    public void errorSimulator() {
        throw new RuntimeException("异常");
    }
}
